package com.wakala.employment.fragment.other;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.broccoli.BroccoliSimpleDelegateAdapter;
import com.wakala.employment.adapter.base.delegate.SimpleDelegateAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentCommunicateMeRecordBinding;
import com.wakala.employment.databinding.FragmentCommunicateWhoRecordBinding;
import com.wakala.employment.fragment.news.NewDetailFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.ArticlePage;
import com.wakala.employment.http.bean.ArticleVo;
import com.wakala.employment.utils.DemoDataProvider;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.tip.ToastUtils;

import me.samlss.broccoli.Broccoli;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CommunicateWhoRecordFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class CommunicateWhoRecordFragment extends BaseFragment<FragmentCommunicateWhoRecordBinding> implements View.OnClickListener {

    private static String TAG = "CommunicateWhoRecordFragment";

    private SimpleDelegateAdapter<ArticleVo> mNewsAdapter;
    int page = 1;
    int pageSize = 10;
    private Integer cid;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public CommunicateWhoRecordFragment() {
        // Required empty public constructor
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected TitleBar initTitle() {
        return null;
    }


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CommunicateWhoRecordFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CommunicateWhoRecordFragment newInstance(String param1, String param2) {
        CommunicateWhoRecordFragment fragment = new CommunicateWhoRecordFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @NonNull
    @Override
    protected FragmentCommunicateWhoRecordBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentCommunicateWhoRecordBinding.inflate(inflater, container, attachToRoot);
    }


    @Override
    protected void initViews() {
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(getContext());
        binding.recyclerView.setLayoutManager(virtualLayoutManager);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        binding.recyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 10);

        mNewsAdapter = new BroccoliSimpleDelegateAdapter<ArticleVo>(R.layout.adapter_news_card_view_list_item, new LinearLayoutHelper(), DemoDataProvider.getEmptyArticleInfo()) {
            @Override
            protected void onBindData(RecyclerViewHolder holder, ArticleVo model, int position) {
                if (model != null) {
                    holder.text(R.id.tv_user_name, model.getUserName());
                    holder.text(R.id.tv_tag, model.getTag());
                    holder.text(R.id.tv_title, model.getTitle());
                    holder.text(R.id.tv_summary, Html.fromHtml(model.getContent(), Html.FROM_HTML_MODE_COMPACT));
                    holder.text(R.id.tv_praise, model.getPraise() == 0 ? "点赞" : String.valueOf(model.getPraise()));
                    holder.text(R.id.tv_comment, model.getComment() == 0 ? "评论" : String.valueOf(model.getComment()));
                    holder.text(R.id.tv_read, "阅读量 " + model.getVisit());
                    holder.image(R.id.iv_image, model.getImageInput());
                    //holder.click(R.id.card_view, v -> Utils.goWeb(getContext(), model.getDetailUrl()));
                   /* ReadNoMoreTextView readNoMoreTextView = holder.findViewById(R.id.tv_summary);
                    readNoMoreTextView.setText(Html.fromHtml(model.getContent(),Html.FROM_HTML_MODE_COMPACT));
                    readNoMoreTextView.setOnReadMoreClickListener(view -> openNewPage(NewDetailFragment.class,"articleId",model.getId()));*/
                    holder.click(R.id.tv_summary, v -> {
                        openNewPage(NewDetailFragment.class, "articleId", model.getId());
                    });
                }
            }

            @Override
            protected void onBindBroccoli(RecyclerViewHolder holder, Broccoli broccoli) {
                broccoli.addPlaceholders(
                        holder.findView(R.id.tv_user_name),
                        holder.findView(R.id.tv_tag),
                        holder.findView(R.id.tv_title),
                        holder.findView(R.id.tv_summary),
                        holder.findView(R.id.tv_praise),
                        holder.findView(R.id.tv_comment),
                        holder.findView(R.id.tv_read),
                        holder.findView(R.id.iv_image)
                );
            }
        };

        DelegateAdapter delegateAdapter = new DelegateAdapter(virtualLayoutManager);
        delegateAdapter.addAdapter(mNewsAdapter);

        binding.recyclerView.setAdapter(delegateAdapter);
    }

    @Override
    protected void initListeners() {
        //下拉刷新
        binding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            getArticleList("fresh", 1);
        });
        //上拉加载
        binding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            int currentPage = mNewsAdapter.getItemCount() / pageSize + 1;
            getArticleList("more", currentPage + 1);
        });
        //设置刷新加载时禁止所有列表操作
        binding.refreshLayout.setDisableContentWhenRefresh(true);
        binding.refreshLayout.setDisableContentWhenLoading(true);
        binding.refreshLayout.autoRefresh();//第一次进入触发自动刷新
    }


    @SuppressLint("CheckResult")
    private void getArticleList(String type, Integer page) {
        XHttpProxy.proxy(TestApi.IArticleService.class)
                .getArticleList(cid, page)
                .subscribeWith(new NoTipRequestSubscriber<ArticlePage>() {
                    @SuppressLint("CheckResult")
                    @Override
                    protected void onSuccess(ArticlePage commonPageApiResult) {
                        Log.i(TAG, "-------------招工信息列表------------------");
                        Log.i(TAG, GsonUtils.toJson(commonPageApiResult));
                        if (type.equals("fresh")) {
                            mNewsAdapter.refresh(commonPageApiResult.getList());
                            binding.refreshLayout.finishRefresh();
                            if (commonPageApiResult.getList().isEmpty()) {
                                ToastUtils.toast("没有符合条件的数据");
                                //binding.llStateful.showEmpty("没有符合条件的数据");
                            } else {
                                // binding.llStateful.showContent();
                            }
                        } else if (type.equals("more")) {
                            if (commonPageApiResult.getList().isEmpty()) {
                                //展示无数据孔状态
                                binding.refreshLayout.finishLoadMoreWithNoMoreData();
                                ToastUtils.toast("已更新到最新数据");
                            } else {
                                mNewsAdapter.loadMore(commonPageApiResult.getList());
                                binding.refreshLayout.finishLoadMore();
                            }

                        }

                        Log.i(TAG, "-------------招工信息列表------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        // binding.refreshLayout.finishLoadMore();
                        ToastUtils.toast(e.getDisplayMessage());
                        if (type.equals("fresh")) {
                            binding.refreshLayout.finishRefresh();
                        } else if (type.equals("more")) {
                            binding.refreshLayout.finishLoadMore();
                        }
                       /* binding.llStateful.showError("加载数据失败", "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                getJobInfoList();
                            }
                        });*/
                        Log.i(TAG, "-------------招工信息列表-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }

                });

    }

    @Override
    public void onClick(View view) {

    }

}